package main

import (
	"chapter-200-etcd/service"
	"log"

	// 标准库
	"context"
	"fmt"
	"time"

	// etcd
	clientv3 "go.etcd.io/etcd/client/v3"
	eresolver "go.etcd.io/etcd/client/v3/naming/resolver"

	// grpc
	"google.golang.org/grpc"
	_ "google.golang.org/grpc/balancer/roundrobin"
	"google.golang.org/grpc/credentials/insecure"
)

const MyService = "xiaoxu/demo"

func main() {
	// 创建 etcd 客户端
	etcdClient, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"192.168.10.20:2379"},
		DialTimeout: 5 * time.Second,
	})

	// 创建 etcd 实现的 grpc 服务注册发现模块 resolver
	etcdResolverBuilder, _ := eresolver.NewBuilder(etcdClient)

	// 拼接服务名称，需要固定义 etcd:/// 作为前缀
	etcdTarget := fmt.Sprintf("etcd:///%s", MyService)

	// 创建 grpc 连接代理
	conn, err := grpc.Dial(
		// 服务名称
		etcdTarget,
		// 注入 etcd resolver
		grpc.WithResolvers(etcdResolverBuilder),
		// 声明使用的负载均衡策略为 roundrobin     grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, roundrobin.Name)),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	)
	defer conn.Close()
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	// 创建 grpc 客户端
	client := service.NewActionClient(conn)
	for {
		// 发起 grpc 请求
		resp, err := client.SayHello(context.Background(), &service.HelloRequest{
			Id: "xiaoxuxiansheng",
		})
		if err != nil {
			log.Fatalf("could not greet: %v", err)
		}
		fmt.Printf("resp: %+v\n", resp)
		// 每隔 1s 发起一轮请求
		<-time.After(time.Second)
	}
}
